package 网络.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * 从代码中可以看出
 *
 * UDP连接是同级的，没有主次之分。 而且是以数据包的形式推送消息
 */
public class UDPServer {
    public static void main(String[] args)  throws  Exception{
        try {
            // 创建一个DatagramSocket对象，监听端口号
            DatagramSocket serverSocket = new DatagramSocket(9876);
            System.out.println("服务器启动，等待接收消息...");

            // 创建一个字节数组，用于存储接收到的数据
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            // 接收数据
            serverSocket.receive(receivePacket);

            // 将字节数据转换为字符串
            String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("服务器收到消息：" + sentence);

            // 向客户端发送响应
            String capitalizedSentence = sentence.toUpperCase();
            byte[] sendData = capitalizedSentence.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());

            serverSocket.send(sendPacket);

            System.out.println("服务器：消息已发送，并转换为大写");

            // 关闭连接
            serverSocket.close();
        } catch (IOException e) {
            System.err.println("服务器异常：" + e.getMessage());
            e.printStackTrace();
        }

    }
}
